package com.example.hasee.lifediary;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import com.example.hasee.mylifediary.DaoMaster;
import com.example.hasee.mylifediary.DaoMaster.DevOpenHelper;
import com.example.hasee.mylifediary.DaoSession;
import com.example.hasee.mylifediary.NoteDao;

import java.util.List;

import de.greenrobot.dao.query.Query;



public class LifeDiary extends ListActivity {
    //Greendao使用的变量
    public static final int MENU_ITEM_INSERT = Menu.FIRST;

    private SQLiteDatabase db;

    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private NoteDao noteDao;

    private Cursor cursor;



//    private EditText et_search;
//    private String search;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diary_list);



        //初始化GreenDAO
        InitDAO();

        //初始化List
        InitList();




//
//        B1.setOnClickListener(new View.OnClickListener(){
//            @Override
//            public void onClick(View view){
//                search_data();
//            }
//        });
    }


    //初始化dao
    private void InitDAO() {
        DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db",
                null);
        db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
        noteDao = daoSession.getNoteDao();

    }

    //初始化List
    private void InitList() {
        String textColumn = NoteDao.Properties.Title.columnName;
        String dateColumn = NoteDao.Properties.Date.columnName;
        String orderBy = dateColumn + " COLLATE LOCALIZED DESC";
        cursor = db.query(noteDao.getTablename(), noteDao.getAllColumns(),
                null, null, null, null, orderBy);
        String[] from = { textColumn, dateColumn };
        int[] to = { R.id.text1, R.id.created };

        final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
                R.layout.diary_row, cursor, from, to);
        setListAdapter(adapter);

        ListView listView = this.getListView();
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, final long id) {
                //定义AlertDialog.Builder对象，当长按列表项的时候弹出确认删除对话框
                AlertDialog.Builder builder = new AlertDialog.Builder(LifeDiary.this);
                builder.setIcon(android.R.drawable.ic_dialog_info);
                builder.setMessage("确定删除?");
                builder.setTitle("提示");

                //添加AlertDialog.Builder对象的setPositiveButton()方法
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        noteDao.deleteByKey(id);
                        Toast.makeText(getBaseContext(),"删除成功",Toast.LENGTH_SHORT).show();
                        onCreate(null);//起刷新作用
                    }
                });

                //添加AlertDialog.Builder对象的setNegativeButton()方法
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.create().show();
                return true;
            }
        });

    }

//    添加选择菜单
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(Menu.NONE, MENU_ITEM_INSERT, 0, R.string.menu_insert);
        menu.add(0,0,0,"退出");
        return true;
    }

    //添加选择菜单的选择事件
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            //插入一条数据
            case MENU_ITEM_INSERT:
                Intent intent0 = new Intent(this, DiaryEditor.class);
                intent0.setAction(DiaryEditor.INSERT_DIARY_ACTION);
                intent0.setData(getIntent().getData());
                startActivity(intent0);
                LifeDiary.this.finish();
                cursor.requery();
                return true;
            case 0:
                System.exit(0);


        }
        return super.onOptionsItemSelected(item);
    }

    protected void onListItemClick(ListView l, View v, int position, long id) {
        // Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
        String mid = Long.toString(id);
        Log.d("id", mid);
        // Intent intent = new Intent();
        // startActivity(new Intent(DiaryEditor.EDIT_DIARY_ACTION, uri));
        Intent intent = new Intent(this, DiaryEditor.class);
        intent.setAction(DiaryEditor.EDIT_DIARY_ACTION);
        Bundle bundle = new Bundle();
        bundle.putLong("id", id);
        intent.putExtras(bundle);
        Log.d("id", mid);
        startActivity(intent);
        LifeDiary.this.finish();
        cursor.requery();
    }

    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        cursor.requery();
        super.onActivityResult(requestCode, resultCode, intent);
        // renderListView();
    }
    // @SuppressWarnings("deprecation")
    // private void renderListView() {
    // Cursor cursor = managedQuery(getIntent().getData(), PROJECTION,
    // null,null, DiaryColumns.DEFAULT_SORT_ORDER);
    //
    // SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
    // R.layout.diary_row, cursor, new String[] { DiaryColumns.TITLE,
    // DiaryColumns.CREATED }, new int[] { R.id.text1,R.id.created });
    // setListAdapter(adapter);
    // }
//    public void search_data(){
//        String textColumn = NoteDao.Properties.Title.columnName;
//        String[] from = { textColumn};
//        ArrayAdapter adapter =new ArrayAdapter(this,android.R.layout.simple_dropdown_item_1line,from);
//        AutoCompleteTextView myA =
//                (AutoCompleteTextView) findViewById(R.id.et_search);
//        myA.setAdapter(adapter);
//    }
//    ArrayAdapter adapter =new ArrayAdapter(this,android.R.layout.simple_dropdown_item_1line,)



}